package com.grts.mall.service;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.grts.mall.common.CommonResult;
import com.grts.mall.mapper.UserMapper;
import com.grts.mall.pojo.User;
import com.grts.mall.pojo.UserExample;
import com.grts.mall.pojo.UserExample.Criteria;
import com.grts.mall.pojo.vo.LoginResultVo;

@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	private UserMapper userMapper;
	
	@Override
	public CommonResult login(User user) {
		String hasPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes()).toUpperCase();
		UserExample example = new UserExample();
		Criteria model = example.createCriteria();
		model.andUserNameEqualTo(user.getUserName());
		model.andPasswordEqualTo(hasPassword);
		List<User> list = this.userMapper.selectByExample(example);
		if (list.size()==0) {
			return CommonResult.error("账户或密码错误");
		}
		LoginResultVo vo = new LoginResultVo();
		BeanUtils.copyProperties(list.get(0), vo);
		return CommonResult.success(vo);
	}

	@Override
	public CommonResult register(User user) {
		List<User> users = this.userMapper.selectByExample(new UserExample());
		for (User user2 : users) {
			if (user.getUserName().equals(user2.getUserName())) {
				return CommonResult.error("此用户名已存在");
			}
		}
		String newpas = DigestUtils.md5DigestAsHex(user.getPassword().getBytes()).toUpperCase();
		user.setPassword(newpas);
		this.userMapper.insert(user);
		return CommonResult.success("注册成功");
	}

	
}
